package com.it.you.file;

import cn.hutool.core.io.FileUtil;

import javax.swing.*;
import java.io.File;
import java.util.List;

/**
 * @Author : YouHui
 * @create 2023/5/29 12:16
 */
public class FileImportWorker extends SwingWorker<Void, Integer> {
    private JProgressBar progressBar;
    private int timeout;
    private String filePath;
    private long lastSuccessfulPosition;

    public FileImportWorker(JProgressBar progressBar, String filePath, int timeout) {
        this.progressBar = progressBar;
        this.filePath = filePath;
        this.timeout = timeout;
    }

    @Override
    protected Void doInBackground() throws Exception {
        long startTime = System.currentTimeMillis();
        // 假设文件总大小为 fileSize
        long fileSize = FileUtil.size(new File(filePath));
        System.out.println("fileSize = " + fileSize);
        long currentPosition = lastSuccessfulPosition;

        while (currentPosition < fileSize) {
            // 检查是否超时
            if (System.currentTimeMillis() - startTime > timeout) {
                throw new Exception("导入超时");
            }
            // 模拟文件导入操作，每次导入一部分
            // 假设每次操作导入 10 字节
            currentPosition += 10;
            int progress = (int) (currentPosition * 100 / fileSize);
            publish(progress);

            // 模拟耗时操作
            Thread.sleep(100);
        }

        return null;
    }

    @Override
    protected void process(List<Integer> chunks) {
        // 更新进度条
        for (Integer progress : chunks) {
            progressBar.setValue(progress);
        }
    }

    @Override
    protected void done() {
        try {
            get();
            JOptionPane.showMessageDialog(null, "导入完成");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "导入失败: " + e.getMessage());
            lastSuccessfulPosition = progressBar.getValue();
            // 如果需要在异常情况下重新启动任务，可以在此处调用`execute()`方法
             this.execute();
        }
    }
}
